package com;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class TicketService {
    private List<Ticket> ticketList = new ArrayList<>();
    private LogService logService;

    public TicketService(LogService logService) {
        this.logService = logService;
    }
    public Ticket sellTicket(Schedule schedule, List<Seat> selectedSeats,
                             boolean isChild, User operator) {
        for (Seat seat : selectedSeats) {
            if (!"空闲".equals(seat.getStatus())) {
                System.out.println("错误：座位" + seat.getRowNum() + "排" + seat.getColNum() + "号已售出");
                return null;                      }
                                        }
        double basePrice = schedule.getPrice();
        double discount = 1.0;
        if (isChild) {
            discount *= 0.5;}
        if (schedule.getShowTime().getHour() < 10) {
            discount *= 0.9;                       }
        double actualPrice = basePrice * discount * selectedSeats.size();

        selectedSeats.forEach(Seat::toggleStatus);

        Ticket ticket = new Ticket(schedule, selectedSeats, actualPrice, isChild);
        ticketList.add(ticket);

        logService.recordLog("售票", operator,
                "影片《" + schedule.getMovie().getTitle() + "》" +
                        selectedSeats.size() + "张，票号：" + ticket.getTicketId());
        return ticket;
    }

    public boolean refundTicket(String ticketId, User operator) {
        for (Ticket ticket : ticketList) {
            if (ticket.getTicketId().equals(ticketId) && !ticket.isRefunded()) {
                LocalDateTime now = LocalDateTime.now();
                long minutesBeforeShow = Duration.between(now, ticket.getSchedule().getShowTime()).toMinutes();
                if (minutesBeforeShow < 60) {
                    System.out.println("错误：距离放映不足1小时，不允许退票");
                    return false;
                }
                double refundFee = ticket.getPrice() * 0.1;
                ticket.setRefundFee(refundFee);
                ticket.setRefunded(true);
                ticket.setRefundTime(now);
                ticket.getSeats().forEach(Seat::toggleStatus);

                logService.recordLog("退票", operator,
                        "票号：" + ticketId + "，手续费：" + refundFee + "元");
                return true;
            }
        }
        System.out.println("错误：票号不存在或已退票");
        return false;
    }

    public List<Ticket> getTicketList() {
        return ticketList;
    }
}